﻿@using System.Data;
@using System.Data.SqlClient;
@using System.Globalization;
 
@{
    ViewBag.Title = "DetallesPropiedad";
    Layout = "~/Views/Shared/_LayoutPublicaciones.cshtml";
    SqlDataReader provincias = (SqlDataReader)ViewBag.provincias;
}
<script type="text/javascript">
    document.body.onload = cambioProvincia;
    function cambioProvincia() {
        document.getElementsByName("sector")[0].value = "";
        $('#municipio').html($.ajax({
            url: "/Propiedades/Municipios/" + $("#provincia").val(),
            async: false
        }).responseText);
        cambioMunicipio();
    }
    var algo;
  
    
   
    function cambioMunicipio() {
        document.getElementsByName("sector")[0].value = "";
        algo = '';
        $.ajax({
            url: "/Propiedades/Sector/" + $('#municipio').val(),
            async: false,
            success: function (text) {
                algo = text;
            }

        });
       
        $("#sector").autocomplete({
            source: ConvertArray(algo)
        });
   //     $('#sector').html($.ajax({
    //        url: "/Propiedades/Sectorr/" + $("#municipio").val(),
     //       async: false,
     //       success: function (text) {
       //         algo = text;
      //      }
     //   }));
  }
  
</script>
 
@using (Html.BeginForm("AgregadoInmueble", "Propiedades", FormMethod.Post))
{
    <br />
    <br />
<h4>Suministre la direccion de la propiedad</h4>
<table border="0">
<tr>
 
</tr>
<tr>
<td>Provincias</td><td><select id="provincia" onchange="cambioProvincia()" name="provincia">
    @while (provincias.Read())
    {
    <option value="@provincias[0].ToString()">@provincias[1].ToString()</option>

    }
        </select>
    </td>
</tr>
<tr>
<td>Municipios</td><td><select id="municipio" onchange="cambioMunicipio()" name="municipio"><option></option></select></td>
</tr>
<tr>
<td>Sector</td><td><input type="text" id="sector" name="sector" /></td>
</tr>
<tr>
<td>Calle, Numero, etc</td><td><textarea rows="2" name="direccion" id="direccion"></textarea></td>
</tr>
 </table>
  <input type="button" value="Sugerencia" onclick="codeAddress()" />
    <br />  
      <br />  
 <form id="location">
<p>Longitud:<input type="text" readonly="true" name="lon" /></p>
<p>Latitud:<input type="text" readonly="true" name="lat" /></p> 
     <a href="#" id="setLocation">Ingresar Coordenada.</a>
</form>   
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <!--Aqui todo lo del mapa-->
 <script language="javascript" type="text/javascript">
     
     var marker;
     var markersArray = [];
     var probar;
     var map;
     var geocoder;

    
     function inicial(locationInicial, zoom) {
         geocoder = new google.maps.Geocoder();

         // var bounds = new google.maps.LatLngBounds();
         var options = {

             zoom: zoom,
             center: locationInicial,

             //   mapTypeId: google.maps.MapTypeId.TERRAIN
             mapTypeId: google.maps.MapTypeId.ROADMAP

         };
         //  googleMap = new google.maps.Map($("#map")[0], options);
         map = new google.maps.Map(document.getElementById("map"), options);

     }

     $(document).ready(function () {
         var point = new google.maps.LatLng('18.4751517', '-69.93458');

         inicial(point, 8);
        // var infoWindow = new google.maps.InfoWindow({ content: "Cargando..." });
    
   
        
       
      //  bounds.extend(point);
      //  AddMarkert(point);
   
     //   google.maps.event.addListener(marker, "click", function () {

     //       infoWindow.setContent(this.html);
     //       infoWindow.open(map, this);
     //   });

        google.maps.event.addListener(map, "click", function (event) {
            // placeMarker(event.latLng);
            //Borramos todos los markert para que solo aparesca el nuevo.
            
             
           
           
            //    document.getElementsByName("lat")[0].value = "ahi"
            AddMarkert(event.latLng,14);
            //

        });
 
       
        //map.fitBounds(bounds);


    });
 

  

     function AddMarkert(location, zoom) {
         inicial(location, zoom);
         DeleteMarkert();
        marker = new google.maps.Marker({
            position: location,
            map: map,
            icon: '/Content/PushPin.png',
        });
        
        var Locat = String(location).replace('(', '').replace(')', '').split(',');
        
       document.getElementsByName("lon")[0].value=Locat[0];
       document.getElementsByName("lat")[0].value = Locat[1];
       markersArray.push(marker);
        
            }

     function DeleteMarkert() {
         if (markersArray) {
             for (i in markersArray) {
                 markersArray[i].setMap(null);
             }
             markersArray.length = 0;
         }

     }

     function codeAddress() {
          
         //var address = document.getElementById("address").value;
        
         var provincia = document.getElementById("provincia").options[document.getElementById("provincia").selectedIndex].text;
             
         var municipio = document.getElementById("municipio").options[document.getElementById("municipio").selectedIndex].text;
         var  sector = document.getElementById("sector").value;
        
         var calle = document.getElementById("direccion").value;
         if (empty(sector)==false && empty(municipio)==false) {
            
             var address = calle + ', ' + sector + ', ' + municipio + ', ' + provincia + ', ' + 'Republica Dominicana';

             geocoder.geocode({ 'address': address }, function (results, status) {
                 if (status == google.maps.GeocoderStatus.OK) {
                     
                     
                      AddMarkert(results[0].geometry.location,14);
                     map.setCenter(results[0].geometry.location);

                 } else {
                     alert("Geocode was not successful for the following reason: " + status);
                 }
             });
         } else {
             alert('Debe completar la direccion.');
         }
    



         }

     
     function empty(e) {
         switch(e) {
             case "":
             case 0:
             case "0":
             case null:
             case false:
             case typeof this == "undefined":
                 return true;
             default : return false;
         }
     }

 

</script>   
    
   <!--Script del pop pup-->
    #region " Script del Pop pup"
 <script>
     $(function() {
         var name = $( "#Latitud" ),
             email = $( "#Longitud" ),
            
             allFields = $( [] ).add( name ).add( email ),
             tips = $( ".validateTips" );
 
         function updateTips( t ) {
             tips
                 .text( t )
                 .addClass( "ui-state-highlight" );
             setTimeout(function() {
                 tips.removeClass( "ui-state-highlight", 1500 );
             }, 500 );
         }
 
         function checkLength( o, n, min, max ) {
             if ( o.val().length > max || o.val().length < min ) {
                 o.addClass( "ui-state-error" );
                 updateTips("El tamaño de la " + n + " debe de estar entre " +
                     min + " y " + max + "caracteres." );
                 return false;
             } else {
                 return true;
             }
         }
 
         function checkRegexp( o, regexp, n ) {
             if ( !( regexp.test( o.val() ) ) ) {
                 o.addClass( "ui-state-error" );
                 updateTips( n );
                 return false;
             } else {
                 return true;
             }
         }
 
         $( "#dialog-form" ).dialog({
             autoOpen: false,
             height: 400,
             width: 350,
             modal: true,
             buttons: {
                 "Buscar": function() {
                     var bValid = true;
                     allFields.removeClass( "ui-state-error" );
 
                    bValid = bValid && checkLength( name, "Latitud", 4, 18 );
                     bValid = bValid && checkLength( email, "Longitud", 4, 18 );
                    
 
                   //  bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                     // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                  //   bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
                    
 
                     if (bValid) {
                         $( "#users tbody" ).append( "<tr>" +
                            "<td>" + name.val() + "</td>" + 
                            "<td>" + email.val() + "</td>" + 
                                                   "</tr>");
                    var locat= new google.maps.LatLng($('#Latitud').val(), $('#Longitud').val());
                    AddMarkert(locat,14);
                        
                        $( this ).dialog( "close" );
                    }
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                allFields.val( "" ).removeClass( "ui-state-error" );
            }
        });
 
         $("#setLocation")
            .button()
            .click(function() {
                $( "#dialog-form" ).dialog( "open" );
            });
    });
    </script>
    #endregion   
    
    #region " Script del Auto complete de los sectores"
    
    
      <script>
          $(function () {
             $("#sector").autocomplete({
                  source:  ConvertArray(algo)
              });
          });
         


          function ConvertArray(json) {
          
              var result = String(json).replace('[', '').replace(']', '');
            //  .replace('[', '').replace(']', '')
              return result.split(',', 1000);


          }

           
    </script>
    #endregion   
    
    
<div id="map" style="width: 700px; height: 400px;"></div>   
    <br />
    <br />
    
    
    <input type="submit" value="Finalizar ingreso de propiedad" />
    <br />
    
    
}

 
 
 <div id="dialog-form" title="Ingrese la Localizacion">
    <p class="validateTips">Debe llenar ambos campos.</p>
 
    <form>
    <fieldset>
        <label for="Latitud">Latitud</label>
        <input type="text" name="Latitud" id="Latitud" class="text ui-widget-content ui-corner-all" />
        <label for="Longitud">Longitud</label>
        <input type="text" name="Longitud" id="Longitud" value="" class="text ui-widget-content ui-corner-all" />
     </fieldset>
    </form>
</div>
 
 <br />
 <br />